<template>
  <slot></slot>
  <div class="xtx-infinite-loading" ref="target">
    <div class="loading" v-show="modelValue">
      <span class="img"></span>
      <span class="text">{{loadingText}}</span>
    </div>
    <div class="none" v-if="finished">
      <span class="img"></span>
      <span class="text">{{ finishedText }}</span>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
export default {
  name: 'XtxInfiniteLoading',
  props: {
    // loading: {
    //   type: Boolean,
    //   default: false
    // },
    modelValue: {
      type: Boolean,
      default: false
    },
    finished: {
      type: Boolean,
      default: false
    },
    finishedText: {
      type: String
    },
    loadingText: {
      type: String
    }
  },
  setup (props, { emit }) {
    // 双向绑定，子组件不需要传数据，因此为空
    emit('update:modelValue')

    const target = ref(null)

    useIntersectionObserver(target, ([{ isIntersecting }], observerElement) => {
      // console.log(isIntersecting)
      // 当元素处于可视界面时，开始请求接口获取数据
      // console.log(isIntersecting)
      if (isIntersecting) {
        if (props.modelValue === false && props.finished === false) {
          emit('load')
        }
      }
    })
    return { target }
  }
}
</script>

<style scoped lang='less'>
.xtx-infinite-loading {
  .loading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 50px;
      height: 50px;
      background: url(~@/assets/images/load.gif) no-repeat center / contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
  .none {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 200px;
      height: 134px;
      background: url(~@/assets/images/none.png) no-repeat center / contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
}
</style>
